import { SoftwareService } from 'app/modules/software/services/software.service';
import { ArrayAPIBase, APIBase } from 'app/modules/base/api-base';
import { Component, OnInit, Input } from '@angular/core';
import { MySelection } from 'app/modules/base/selection';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { ReplaySubject } from 'rxjs/internal/ReplaySubject';
import { ActivatedRoute } from '@angular/router';
import { map, startWith } from 'rxjs/operators';

@Component({
  selector: 'm-restrict-app',
  templateUrl: './restrict-app.component.html',
  styleUrls: ['./restrict-app.component.scss'],
  providers: [
    {
      multi: true,
      provide: NG_VALUE_ACCESSOR,
      useExisting: RestrictAppComponent,
    },
  ],
})
export class RestrictAppComponent<T extends { id: number, name: string, package_name: string }>
  implements OnInit, ControlValueAccessor {
  constructor(private software: SoftwareService, private route: ActivatedRoute) {}

  @Input() editing = false;
  @Input() headText: string;
  selection = new MySelection<T>('id');
  values$ = new ReplaySubject(1);
  dataSource: APIBase<any, T>;

  selectedService$ = this.selection.change.pipe(
    startWith(this.selection.selected),
    map(() => {
      const selectedItems = this.selection.selected;
      const items = selectedItems.map(item => {
        if (item.id) {
          return {
            id: item.id,
            app_id: item.id,
            title: item.name,
            package_name: item.package_name
          }
        } else {
          return item;
        }
      })
      const datasource = new ArrayAPIBase(items);
      datasource.search = (obj: any, keyword: string) => {
        keyword = keyword.toLowerCase();
        if (obj.title && obj.title.toLowerCase().includes(keyword)) {
          return true;
        }
        return false;
      };
      items.sort((prevItem, nextItem) => {
        return prevItem.id - nextItem.id;
      });
      this.values$.next(items);
      return datasource;
    }),
  );

  ngOnInit() {
    let r = this.route;
    while (r.firstChild) {
      r = r.firstChild;
    }
    this.dataSource = this.software.resource();
  }

  writeValue(data: T[]): void {
    this.selection.clear();
    //默认选中
    if (data) {
      data.forEach((item) => {
        item.id = item['app_id'];
        item.name = item['title'];
        this.selection.select(item);
      });
    }
  }

  registerOnChange(fn: any): void {
    this.values$.subscribe(fn);
  }

  registerOnTouched(fn: any): void {}

  setDisabledState?(isDisabled: boolean): void {}
}
